const express = require('express')
const app = express()
const cors = require('cors')
const { log } = require('console')

const port = 3000

// app.get('/', (req, res) => {
//   res.send('Hello World!')
// })

app.use(express.static('public'))
app.use(cors())

app.get('/sse', (req, res) => {
    res.set({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive'
    });
  
    res.flushHeaders();
  
    setInterval(() => {
    //   const data = {
    //     message: `Current time is ${new Date().toLocaleTimeString()}`
    //   };
  
    //   res.write(`data: ${JSON.stringify(data)}\n\n`);

    // index.js文件
const fs = require('fs');

    // 1.异步读取文件
    fs.readFile('./public/video.json','utf-8', function(error, data) {
        if(error)  return;
        var videosObject = {};
        console.log(JSON.parse(data))
        Object.keys(JSON.parse(data)).forEach((items,index) => {
            console.log(JSON.parse(data)[items])
            
            videosObject[items] = '/videos/' + Object.values(JSON.parse(data))[index]
            //     {items: Object.values(JSON.parse(data))[index]}
            // )
            // JSON.parse(data)[items] = 
            //  = Object.values(JSON.parse(data))[index]
        });

        console.log(videosObject)
        console.log(Object.values(JSON.parse(data)))
        // console.log(data.toString());  // this is a message!

        res.write(`data: ${JSON.stringify(videosObject)}\n\n`);
    })

    }, 1000);
  });
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})